package com.mec.taskassign.utils;


import com.mec.taskassign.model.Place;

import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GeodeticCurve;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Component
public class CommonUtils {
    //规定车速
    @Value(value = "${common-values.script-path}")
    public String scriptPath;

    @Value(value = "${common-values.car-speed}")
    public float carSpeed;


    public Place[] transferListToArray(List<Place> list) {
        Place[] place = new Place[list.size()];
        for (int i = 0; i < list.size(); i++) {
            place[i] = list.get(i);
        }
        return place;
    }

    public double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo, Ellipsoid ellipsoid) {
        //创建GeodeticCalculator，调用计算方法，传入坐标系、经纬度用于计算距离
        GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo);
        return geoCurve.getEllipsoidalDistance();
    }

    public List<Place> fillPlacesBlank(List<Place> allPlaces) {
        int maxId = 0;
        for (Place onePlace : allPlaces) {
            if (onePlace.getId() > maxId) {
                maxId = onePlace.getId();
            }
        }
        System.out.println(maxId);
        for (int i = 1; i <= maxId; i++) {
            boolean check = false;
            for (Place onePlace : allPlaces) {
                if (i == onePlace.getId()) {
                    check = true;
                    break;
                }
            }
            if (!check) {
                Place place = new Place(i, 0, 0, 0, 0, 0, 0, "NULL");
                allPlaces.add(i - 1, place);
            }
        }
        return allPlaces;
    }

    /**
     * @param twoDimension 时间距离矩阵二维数组
     * @param allPlaces    所有存在的地点
     * @return 处理后的矩阵
     */
    public float[][] processDistancesWithMachineLearning(float[][] twoDimension, List<Place> allPlaces) {
        float[][] processedTwoDimension = new float[twoDimension.length][twoDimension[0].length];
        StringBuilder regionSeqStr = new StringBuilder();
        //将区域序列以“-”分开
        for (int i = 0; i < allPlaces.size(); i++) {
            if (i != allPlaces.size() - 1) {
                regionSeqStr.append(getRegionId(allPlaces.get(i).getId(), allPlaces)).append("-");
            } else {
                regionSeqStr.append(getRegionId(allPlaces.get(i).getId(), allPlaces));
            }
        }
//        System.out.println(Arrays.toString(allPlaces.toArray()));
//        System.out.println(regionSeqStr.toString());
        //根据处理的区域序列获取拥堵系数矩阵
        float[][] coefficientMatrix = congestionEstimation_python_new(regionSeqStr.toString(), allPlaces.size());
        for (int i = 0; i < coefficientMatrix.length; i++) {
            for (int j = 0; j < coefficientMatrix[i].length; j++) {
                System.out.print(coefficientMatrix[i][j] + " ");
            }
            System.out.println();
        }
        //将拥堵矩阵应用到原二维时间距离矩阵上
        int coeffi_index_row = 0; //系数矩阵行索引
        int coeffi_index_column = 0;  //稀疏矩阵列索引
        for (int i = 0; i < twoDimension.length; i++) {
            //判断行索引是否有效
            if (isValidIndex(i, allPlaces)) {
                for (int j = 0; j < twoDimension[i].length; j++) {
                    //判断列索引是否有效
                    if (isValidIndex(j, allPlaces)) {
                        processedTwoDimension[i][j] = twoDimension[i][j] *
                                coefficientMatrix[coeffi_index_row][coeffi_index_column];
                        coeffi_index_column++;
                    }
                    //列索引无效
                    else {
                        processedTwoDimension[i][j] = (float) 999999.99;
                    }
                }
                coeffi_index_row++;
            }
            //行索引无效
            else {
                for (int j = 0; j < twoDimension[i].length; j++) {
                    processedTwoDimension[i][j] = (float) 999999.99;
                }
            }
            coeffi_index_column = 0;

        }


//        for(int i=0;i<twoDimension.length;i++){
//            for(int j=0;j<twoDimension[i].length;j++){
//                //判断索引是否存在
//                if(isValidIndex(i,allPlaces) && isValidIndex(j,allPlaces)){
//                    int startId=getRegionId(i,allPlaces);
//                    int endId=getRegionId(j,allPlaces);
//                    //对于时间距离进行更改
//                    processedTwoDimension[i][j]=twoDimension[i][j]*congestionEstimation_python(startId,endId);
//
//                }
//                else {
//                    processedTwoDimension[i][j]= (float) 99999.99;
//                }
//            }
//        }
        return processedTwoDimension;
    }

    /**
     * 判断这个索引是否存在
     *
     * @param index         被检测索引
     * @param allPlacesList 所有存在点的集合
     * @return 是否存在
     */
    public boolean isValidIndex(int index, List<Place> allPlacesList) {
        boolean check = false;
        for (Place place : allPlacesList) {
            if (index == place.getId()) {
                check = true;
                break;
            }
        }
        return check;
    }

    /**
     * 用于返回给定任务的区域序号
     *
     * @param taskId    任务id
     * @param allPlaces 所有地点列表
     * @return 所在区域id
     */
    public int getRegionId(int taskId, List<Place> allPlaces) {
        float taskLongitude = 0;
        float taskLatitude = 0;
        //获取任务的经纬度
        for (Place onePlace : allPlaces) {
            if (taskId == onePlace.getId()) {
                taskLongitude = onePlace.getJing();
                taskLatitude = onePlace.getWei();
            }
        }
        //获取最大最小经纬度
        List<Float> longitudeList = new ArrayList<>();
        List<Float> latitudeList = new ArrayList<>();
        for (Place onePlace : allPlaces) {
            longitudeList.add(onePlace.getJing());
            latitudeList.add(onePlace.getWei());
        }
        float minLongitude = Collections.min(longitudeList);
        float maxLongitude = Collections.max(longitudeList);
        float minLatitude = Collections.min(latitudeList);
        float maxLatitude = Collections.max(latitudeList);
        float longitudeDifference = maxLongitude - minLongitude;
        float latitudeDifference = maxLatitude - minLatitude;
        //获取区域对应
        int offsetX = 0;
        int offsetY = 0;
        //从左到右1，2，3，4
        if (taskLongitude - minLongitude < 0.25 * longitudeDifference) {
            offsetX = 1;
        } else if (taskLongitude - minLongitude >= 0.25 * longitudeDifference && taskLongitude - minLongitude < 0.5 * longitudeDifference) {
            offsetX = 2;
        } else if (taskLongitude - minLongitude >= 0.5 * longitudeDifference && taskLongitude - minLongitude < 0.75 * longitudeDifference) {
            offsetX = 3;
        } else if (taskLongitude - minLongitude >= 0.75 * longitudeDifference && taskLongitude - minLongitude <= 1 * longitudeDifference) {
            offsetX = 4;
        }
        //从上到下4,3,2,1
        if (taskLatitude - minLatitude < 0.25 * latitudeDifference) {
            offsetY = 4;
        } else if (taskLatitude - minLatitude >= 0.25 * latitudeDifference && taskLatitude - minLatitude < 0.5 * latitudeDifference) {
            offsetY = 3;
        } else if (taskLatitude - minLatitude >= 0.5 * latitudeDifference && taskLatitude - minLatitude < 0.75 * latitudeDifference) {
            offsetY = 2;
        } else if (taskLatitude - minLatitude >= 0.75 * latitudeDifference && taskLatitude - minLatitude <= 1 * latitudeDifference) {
            offsetY = 1;
        }
        //根据坐标计算出区域id
        return (offsetY - 1) * 4 + offsetX;
    }


    //利用脚本返回拥堵系数
    public float[][] congestionEstimation_python_new(String regionSeq, int coefficientSize) {

//        String scriptPath="D:\\Study\\ProgrammingProject\\PycharmProject\\WangGuan\\201230_MEC_PYTHON\\estimateAllCongestion.py";
        //需要estimateAllCongestion.py的绝对目录

//        String scriptPath="D:\\Study\\ProgrammingProject\\IDEAProject\\WangGuan\\201230_MEC_JAVA\\task-assign\\src\\main\\java\\com\\mec\\taskassign\\machine_learning\\estimateAllCongestion.py";

        float[][] coeff_matrix = new float[coefficientSize][coefficientSize];
        //调用脚本
        System.out.println(">>>>>>>>Start using Python script<<<<<<<<");
        System.out.println("Python script path: " + scriptPath);
//        System.out.println("speed: "+ commonValues.carSpeed + 1);
        String[] args = new String[]{"python", scriptPath,
                regionSeq};
        try {
            //调用命令行进行执行
            Process process = Runtime.getRuntime().exec(args);
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    process.getInputStream(), "gbk"
            ));
            String line;
            int count = 0; //标注第几行
            while ((line = in.readLine()) != null) {
                String[] lineSplit = line.split(" ");
                for (int k = 0; k < lineSplit.length; k++) {
                    coeff_matrix[count][k] = Float.parseFloat(lineSplit[k]);
                }
                count++;
            }

            in.close();
            int waitFor = process.waitFor();
            System.out.println(">>>>>>>>Using completed; waitFor = " + waitFor + "<<<<<<<<<<");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return coeff_matrix;
    }
}
